package com.xinchuang.domain.vo.df;

import com.xinchuang.domain.type.NormalOutQuotationaSubEnum;
import com.xinchuang.utils.BigdecimalUtil;
import com.xinchuang.utils.CheckUtil;
import lombok.Data;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;

/**
 * 热处理费
 */
@Data
public class DfHeatTreatmentCost {
    private List<ItemHeat> dataList;

    private double subTotal;

    public void checkHeatTreatmentCost() {
        BigDecimal subTotalAfter = new BigDecimal(0.00);
        String strType = NormalOutQuotationaSubEnum.HEAT_TREATMENT.getCn();
        //校验明细
        this.dataList.stream().allMatch(dataList -> {
            String type = strType + " " + dataList.getItemName() + " 金额";
            return CheckUtil.checkIsEqual(type, dataList.getTotalPrice(), BigdecimalUtil.calculateTotalPrice(dataList.getPrice(), dataList.getWeight()).doubleValue());
        });
        //检验小计
        for (ItemHeat item : this.getDataList()) {
            BigDecimal totalPrice = calculateTotalPrice(item.getPrice(), item.getWeight());
            subTotalAfter = subTotalAfter.add(totalPrice);
        }
        checkSubTotal(strType, this.getSubTotal(), subTotalAfter.setScale(2, RoundingMode.HALF_UP));
    }

    /**
     * 计算总价
     *
     * @param price
     * @param weight
     * @return
     */
    private BigDecimal calculateTotalPrice(Double price, Double weight) {
        BigDecimal num1 = new BigDecimal(price).multiply(new BigDecimal(weight)).setScale(2, RoundingMode.HALF_UP);;
        return num1;
    }


    /**
     * 验证小计是否一致
     *
     * @param type
     * @param subTotal
     * @param subTotalAfter
     */
   private void checkSubTotal(String type, Double subTotal, BigDecimal subTotalAfter) {
        if (subTotalAfter.compareTo(BigDecimal.valueOf(subTotal)) != 0) {
            throw new RuntimeException(type + "-小计计算结果不一致。结果为" + subTotalAfter);
        }
    }
}
